/*
 * (C) 2014-2015 Alibaba Group Holding Limited
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 *
 *
 *     __  ___   ______        ___       __          ___
 *    |  |/  /  /  __  \      /   \     |  |        /   \
 *    |  '  /  |  |  |  |    /  ^  \    |  |       /  ^  \
 *    |    <   |  |  |  |   /  /_\  \   |  |      /  /_\  \
 *    |  .  \  |  `--'  |  /  _____  \  |  `----./  _____  \
 *    |__|\__\  \______/  /__/     \__\ |_______/__/     \__\
 *
 *
 *
 */
//
// Created by KOALA TEAM on 12/19/14.
//

#import "UIImage+KLCrop.h"
#import <AVFoundation/AVFoundation.h>

@implementation UIImage (KLCrop)



//处理

+ (CGRect) calcCropRectInImage:(CGSize)imageSize gravity:(NSString*)gravity viewFrame:(CGRect)viewFrame cropRect:(CGRect)cropRect{
    
    CGSize viewSize = viewFrame.size;
    CGFloat screenRatio = viewSize.height / viewSize.width ;
    CGFloat imageRatio = imageSize.height /imageSize.width;
    
    CGRect presentImageRect = viewFrame;
    CGFloat scale = 1.0;
    
    CGFloat presentImageWidth = 0.0f;
    CGFloat presentImageHeigth = 0.0f;

    
    if([AVLayerVideoGravityResizeAspect isEqual: gravity]){
        
        presentImageWidth = imageSize.width;
        presentImageHeigth = imageSize.height;
        if(screenRatio > imageRatio){
            presentImageWidth = viewSize.width;
            presentImageHeigth = presentImageWidth * imageRatio;
            
        }else{
            presentImageHeigth = viewSize.height;
            presentImageWidth = presentImageHeigth / imageRatio;
        }
        
        presentImageRect.size = CGSizeMake(presentImageWidth, presentImageHeigth);
        presentImageRect.origin = CGPointMake((viewSize.width-presentImageWidth)/2.0, (viewSize.height-presentImageHeigth)/2.0);
        
    }else if([AVLayerVideoGravityResizeAspectFill isEqual:gravity]){
        
        presentImageWidth = imageSize.width;
        presentImageHeigth = imageSize.height;
        if(screenRatio > imageRatio){
            presentImageHeigth = viewSize.height;
            presentImageWidth = presentImageHeigth / imageRatio;
        }else{
            presentImageWidth = viewSize.width;
            presentImageHeigth = presentImageWidth * imageRatio;
        }
        
        presentImageRect.size = CGSizeMake(presentImageWidth, presentImageHeigth);
        presentImageRect.origin = CGPointMake((viewSize.width-presentImageWidth)/2.0, (viewSize.height-presentImageHeigth)/2.0);
        
    }else{
        //        NSAssert(0, @"dont support:%@",gravity);
    }
    
    scale = CGRectGetWidth(presentImageRect) / imageSize.width;
    
    CGRect rect = cropRect;
    rect.origin = CGPointMake(CGRectGetMinX(cropRect)-CGRectGetMinX(presentImageRect), CGRectGetMinY(cropRect)-CGRectGetMinY(presentImageRect));
    
    rect.origin.x /= scale;
    rect.origin.y /= scale;
    rect.size.width /= scale;
    rect.size.height  /= scale;
    
    return rect;
}


- (UIImage*) cropImageWithGravity:(NSString *)gravity  viewRect:(CGRect)bounds  cropRect:(CGRect)cropRect gray:(BOOL) isGraySpace{
    CGSize size = [self size];
    CGRect imageCropRect = [UIImage calcCropRectInImage:size gravity:gravity viewFrame:bounds cropRect:cropRect];
    
    if(!isGraySpace){
        CGImageRef imageRef =  CGImageCreateWithImageInRect(self.CGImage, imageCropRect);
        UIImage* retImage = [UIImage imageWithCGImage:imageRef];
        
        CGImageRelease(imageRef);
        
        return retImage;
    }
    
//    [self scale]
    
    float scale = 1.0;//fminf(1.0f, fmaxf(SUBSET_SIZE/CGRectGetWidth(imageCropRect), SUBSET_SIZE/CGRectGetHeight(imageCropRect)));
    CGPoint offset = CGPointMake(-imageCropRect.origin.x, -imageCropRect.origin.y);
    
    size_t subsetWidth = imageCropRect.size.width * scale;
    size_t subsetHeight = imageCropRect.size.height * scale;
    
    
    CGColorSpaceRef space = CGColorSpaceCreateDeviceGray();
    CGContextRef ctx = CGBitmapContextCreate(nil,
                                             subsetWidth,
                                             subsetHeight,
                                             8,
                                             0,
                                             space,
                                             kCGImageAlphaNone|kCGBitmapByteOrderDefault);
    CGColorSpaceRelease(space);
    CGContextSetInterpolationQuality(ctx, kCGInterpolationNone);
    CGContextSetAllowsAntialiasing(ctx, false);
    
    // adjust the coordinate system
    CGContextTranslateCTM(ctx, 0.0, subsetHeight);
    CGContextScaleCTM(ctx, 1.0, -1.0);
    
    
    UIGraphicsPushContext(ctx);
    CGRect rect = CGRectMake(offset.x * scale, offset.y * scale, scale * size.width, scale * size.height);
    
    [self drawInRect:rect];
    
    UIGraphicsPopContext();
    
    CGContextFlush(ctx);
    CGImageRef subsetImageRef = CGBitmapContextCreateImage(ctx);
    UIImage* subsetImage = [UIImage imageWithCGImage:subsetImageRef];
    CGImageRelease(subsetImageRef);
    CGContextRelease(ctx);
    
    
    return subsetImage;
    
}

- (UIImage*) cropImageWithGravity:(NSString *)gravity  viewRect:(CGRect)bounds  cropRect:(CGRect)cropRect toSize:(CGSize)toSize gray:(BOOL) isGraySpace{
    CGSize size = [self size];
    CGRect imageCropRect = [UIImage calcCropRectInImage:size gravity:gravity viewFrame:bounds cropRect:cropRect];
    
    if(!isGraySpace){
        CGImageRef imageRef =  CGImageCreateWithImageInRect(self.CGImage, imageCropRect);
        UIImage* retImage = [UIImage imageWithCGImage:imageRef];
        CGImageRelease(imageRef);
        UIGraphicsBeginImageContext(toSize);
        [retImage drawInRect:CGRectMake(0, 0, toSize.width, toSize.height)];
        UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return scaledImage;
        
    }else{
        CGPoint offset = CGPointMake(-imageCropRect.origin.x, -imageCropRect.origin.y);
        
        size_t subsetWidth = toSize.width;
        size_t subsetHeight = toSize.height;
        
        
        CGColorSpaceRef space = CGColorSpaceCreateDeviceGray();
        CGContextRef ctx = CGBitmapContextCreate(nil,
                                                 subsetWidth,
                                                 subsetHeight,
                                                 8,
                                                 0,
                                                 space,
                                                 kCGImageAlphaNone|kCGBitmapByteOrderDefault);
        CGColorSpaceRelease(space);
        CGContextSetInterpolationQuality(ctx, kCGInterpolationNone);
        CGContextSetAllowsAntialiasing(ctx, false);
        
        // adjust the coordinate system
        CGContextTranslateCTM(ctx, 0.0, subsetHeight);
        CGContextScaleCTM(ctx, 1.0, -1.0);
        
        
        UIGraphicsPushContext(ctx);
        CGRect rect = CGRectMake(offset.x, offset.y, imageCropRect.size.width, imageCropRect.size.height);
        
        [self drawInRect:rect];
        
        UIGraphicsPopContext();
        
        CGContextFlush(ctx);
        CGImageRef subsetImageRef = CGBitmapContextCreateImage(ctx);
        UIImage* subsetImage = [UIImage imageWithCGImage:subsetImageRef];
        CGImageRelease(subsetImageRef);
        CGContextRelease(ctx);
        
        
        return subsetImage;
    }
}

-(UIImage*) scaleToSize:(CGSize)size{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    
    // 绘制改变大小的图片
    [self drawInRect:CGRectMake(0, 0, size.width, size.height)];
    
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    
    // 返回新的改变大小后的图片
    return scaledImage;
}



@end
